<?php

/*
 * CopyRight  : (C)2012-2099 HaoTeam Inc.
 * Document   : ApiWeChatToken.php
 * Created on : 2021-2-27 16:18:39
 * Author     : Tiger <1192851302@qq.com>
 * Description: This is NOT a freeware, use is subject to license terms.
 *              这即使是一个免费软件,使用时也请遵守许可证条款,得到当时人书面许可.
 *              未经书面许可,不得翻版,翻版必究;版权归属 HaoTeam Inc;
 */

namespace haoteam\http\middleware;

use app\Request;
use app\api\model\WechatUser;

/**
 * Api鉴权中间件
 * Class ApiWeChat
 * Tiger <1192851302@qq.com> 2021-2-27 16:18:39
 */
class ApiWeChatToken {

    /**
     * 
     * @author Tiger <1192851302@qq.com>
     * @param Request $request
     * @param \Closure $next
     * @return type
     */
    public function handle(Request $request, \Closure $next, bool $force = true) {
        $token = trim($request->header('token'));
        $WechatUser = new WechatUser();
        try {
            [$user, $type] = $WechatUser->parseToken($token);
        } catch (\Exception $e) {
            if ($force) {
                return app('json')->make($e->getCode(), $e->getMessage());
            }
        }

        Request::macro('user', function () use (&$user) {
            return !is_null($user) ? $user : [];
        });
        Request::macro('token', function () use (&$token) {
            return !is_null($token) ? $token : '';
        });

        Request::macro('mid', function () use (&$user) {
            return !is_null($user) ? $user['mid'] : 0;
        });

        Request::macro('uid', function () use (&$user) {
            return $user['id'] ?? 0;
        });

        Request::macro('isLogin', function () use (&$user) {
            return !is_null($user);
        });

        return $next($request);
    }

}
